package com.example.demo.api.error;

import com.example.demo.service.exception.ErrorCode;
import com.example.demo.service.exception.ServiceException;
import com.example.demo.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @author zzz
 * @Title: GlobalDefultExceptionHandler
 * @ProjectName test
 * @Description: TODO(统一异常处理)
 * @date 2018/7/12
 */

@ControllerAdvice
public class GlobalDefultExceptionHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalDefultExceptionHandler.class);

    /*@ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", e);
        mav.addObject("url", req.getRequestURL());
        mav.setViewName("error");
        return mav;
    }*/

    /*@ExceptionHandler(value = ServiceException.class)
    @ResponseBody
    public ErrorResult jsonErrorHandler(HttpServletRequest req, ServiceException e) throws Exception {
        e.printStackTrace();
        return ResultUtil.error(e.errorCode.code,e.errorCode.message);
    }*/
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ErrorResult jsonErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        e.printStackTrace();
        if (e instanceof  ServiceException){
            ServiceException serviceException = (ServiceException) e;
            LOGGER.info(serviceException.errorCode.message);
            return ResultUtil.error(serviceException.errorCode.code,serviceException.errorCode.message);
        }
        LOGGER.info(ErrorCode.SYSTEM_ERROR.message);
        return ResultUtil.error(ErrorCode.SYSTEM_ERROR);
    }
}
